package cn.fzkj.springcloud.controller;

import cn.fzkj.springcloud.entity.CommonResult;
import cn.fzkj.springcloud.entity.Payment;
import cn.fzkj.springcloud.loadbalance.ILoad;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class OrderController {

//    private static final String URL = "http://localhost:8001";
    private static final String URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ILoad load;
    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 服务消费方，远程调用服务提供方
     * @param payment
     * @return
     */
    @PostMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(URL + "/payment/create", payment, CommonResult.class);
    }

    /**
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/consumer/payment/getPayment/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(URL + "/payment/getPaymentById/" + id, CommonResult.class);
    }

    @GetMapping(value = "/consumer/loadbalance")
    public String get(){
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
//        System.out.println(instances);
        ServiceInstance instance = load.getInstance(instances);
        System.out.println(instance.getInstanceId() + "\t" + instance.getHost());
        return "instance port is -> " + instance.getPort();
    }

}
